package com.hoperun.product.activity;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;

import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hoperun.product.Models.UserModel;
import com.hoperun.product.base.MIP_BaseActivity;
import com.hoperun.product.common.GlobalState;
import com.hoperun.product.common.Setting;
import com.hoperun.product.common.TableNo;
import com.hoperun.product.entity.LoginEntity;
import com.hoperun.product.entity.SpinnerEntity;
import com.hoperun.product.entity.UserBean;
import com.hoperun.product.net.IServiceImpl;
import com.hoperun.product.net.RequestServiceImpl;
import com.hoperun.product.net.WebServiceAccessUtils;
import com.hoperun.product.util.MD5Encrypt;
import com.hoperun.product.util.ParseUtils;
import com.hoperun.product.util.SharedPreUtil;
import com.hoperun.product.util.scan.ScanGun;
import com.hoperun.product.util.scan.ScanGun.ScanGunCallBack;
import com.hoperun.product.view.SimpleDialog;

import com.hoperun.product.wgyutil.WgyUtil;
import com.hoperun.yieldmgr.R;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;

import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends MIP_BaseActivity implements OnClickListener {
	private static int REQUEST_EXTERNAL_STRONGE = 1;
	JSONObject result=null;
	private Button loginBtn;
	private EditText accountEt;
	private EditText passwordEt;
	private Spinner mBmmcSp;
	//车间下拉框适配器
	private ArrayAdapter<String> mBmmcSpAdapter;
	//记录存储车间的text值
	private List<String> mBmmcList = new ArrayList<String>();
	//记录车间数据字典
	List<SpinnerEntity> mSpinnerList=new ArrayList<SpinnerEntity>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_activity);
		//initDate();
		initView();
		initEvent();

		//selectDict();
		//RequestServiceImpl.checktupdate(mMIPHandler, IServiceImpl.updateapk);

		//wgyccc();
	}

//	private void initDate() {
//		// 保存assets目录下的aonfig.cml文件保存到SD卡
//		String cName = Setting.configName;
//		File cFile = new File(Setting.configFileDir + cName);
//		if (cFile != null && !cFile.exists()) {
//			Setting.CopyAssets(LoginActivity.this, cName, Setting.configFileDir);
//		}
//		Setting.parseXml(Setting.configFileDir + cName);
//
//		// 初始化列表中第一个数据为“请选择”
//				//mBmmcList.add("请选择车间");
//		mSpinnerList.add(new SpinnerEntity("请选择车间", ""));
//	}

	private void initView() {
		loginBtn = (Button) findViewById(R.id.login_loginBtn);
		accountEt = (EditText) findViewById(R.id.login_accountEt);
		passwordEt = (EditText) findViewById(R.id.login_passwordEt);
		//mBmmcSp = (Spinner) findViewById(R.id.login_bmmcSp);
		// 设置车间下拉框适配器 数据来源于访问服务器的数据字典
//		mBmmcSpAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, mBmmcList);
//		mBmmcSpAdapter.setDropDownViewResource(R.layout.spinner_drop_item);
//		mBmmcSp.setAdapter(mBmmcSpAdapter);
//
		accountEt.setFocusable(true);  
		accountEt.setFocusableInTouchMode(true);  
		
		accountEt.requestFocus();
		accountEt.requestFocusFromTouch();
		accountEt.findFocus();
	}

	
	private void initEvent() {
		loginBtn.setOnClickListener(this);
//		accountEt.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
//		accountEt.setOnEditorActionListener(new OnEditorActionListener() {
//
//			@Override
//			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//				
//				if (actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//					//toast(actionId + "");
//					startLoginByScan();
//					return true;
//				}
//
//				return false;
//			}
//		});
//		accountEt.setOnKeyListener(new OnKeyListener() {
//
//			@Override
//			public boolean onKey(View v, int keyCode, KeyEvent event) {
//				if (event != null && event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//					//toast(actionId + "");
//					startLoginByScan();
//				}
//				return false;
//			}
//		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_loginBtn:
			startLogin();
			break;
		}
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		
		Log.e("dispatchKeyEvent", event.getKeyCode() + "");
		// toast("dispatchKeyEvent" + event.getKeyCode() + "");
		// 拦截物理键盘事件
		// if (event.getKeyCode() >= KeyEvent.KEYCODE_0 && event.getKeyCode() !=
		// KeyEvent.KEYCODE_DEL) {
		// if (event.getAction() == KeyEvent.ACTION_DOWN) {
		// mScanGun.isMaybeScanning(event.getKeyCode(), event);
		// return true;
		// }
		// return true;
		// }
		// 拦截回车键，成功解决焦点跳行的问题
//		if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
//
//			return true;
//		}
		return super.dispatchKeyEvent(event);
	}
	/**
	 * 通过扫描的方式登陆
	 */
//	private void startLoginByScan() {
//
//		String account = accountEt.getText().toString().trim();
//
//		String password = MD5Encrypt.MD5(passwordEt.getText().toString().trim());
//
//
//		if(TextUtils.isEmpty(password)){
//			password=MD5Encrypt.MD5("abc123");
//		}
//
//
//		String bmmc="";
//		//车间不是必选项
//		int position =mBmmcSp.getSelectedItemPosition();
//		if(position<0){
//			SimpleDialog.show(this, "登录失败，服务器连接异常！");
//			return;
//		}
//			bmmc = mSpinnerList.get(position).fieldValue;
//
//		if (TextUtils.isEmpty(account)) {
//			toast("请输入工号！");
//			return;
//		}
//		if (TextUtils.isEmpty(password)) {
//			toast("请输入密码！");
//			return;
//		}
//		login(account,password,bmmc);
//	}
	
	/**
	 * 开始登陆，正常手动输入
	 */
	private void startLogin() {
		//accountEt.setText("admin");
		//passwordEt.setText("abc123");

		String account = accountEt.getText().toString().trim();

		//String password = MD5Encrypt.MD5(passwordEt.getText().toString().trim());
		String bmmc="";
		//车间不是必选项
//		int position =mBmmcSp.getSelectedItemPosition();
//		if(position<0){
//			SimpleDialog.show(this, "登录失败，服务器连接异常！");
//			return;
//		}
//			bmmc = mSpinnerList.get(position).fieldValue;
//
		if (TextUtils.isEmpty(account)) {
			toast("请输入工号！");
			return;
		}
//		if (TextUtils.isEmpty(password)) {
//			toast("请输入密码！");
//			return;
//		}
		login(account,"",bmmc);
	}
	
	/**
	 * 登录
	 * @param account
	 * @param password
	 * @param bmmc
	 */
	private void login(String account,String password,String bmmc){
		showWait();
		RequestServiceImpl.login(mMIPHandler, IServiceImpl.LOGIN_R, account, password,bmmc);
	}
	
	/**
	 * 获取车间下拉框值
	 */
//	private void selectDict() {
//		showWait();
//		RequestServiceImpl.selectDict(mMIPHandler, IServiceImpl.SELECTDICT, TableNo.BMMC);
//	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//根据请求是否通过的返回码进行判断，然后进一步运行程序
		if (grantResults.length > 0 && requestCode == REQUEST_EXTERNAL_STRONGE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
			writerSD();
		}

	}
	@Override
	public void onPostHandle(int requestType, Object objBody, boolean error) {
		stopWait();
		String opt = "";
		if (error) {
			switch (requestType) {
				case IServiceImpl.LOGIN_R:
					try {
						// 需注意这里判断登录失败不能去解析json，服务端只会返回单字符串“FALSE”
						JSONObject jsonObj = new JSONObject((String) objBody);
						if (jsonObj.getInt("Code")==0) {
							JSONObject userbeanObj = jsonObj.optJSONObject("Result");
							// 保存userbean数据到本地，格式为json字符串
							SharedPreUtil.putValue(this, SharedPreUtil.USERBEAN, userbeanObj.toString());

							Intent intent = new Intent(this, MainActivity.class);
							startActivity(intent);

							// finish();
						} else {
							SimpleDialog.show(this, jsonObj.getString("Message"));
						}

					} catch (Exception e) {
						e.printStackTrace();
						toast("数据异常");
					}
					break;
//				case IServiceImpl.updateapk://更新
//					try{
//						JSONObject jsonObj = new JSONObject((String) objBody);
//						if (jsonObj.getInt("Code")==0) {
//
//							result=jsonObj.optJSONObject("Result");
//							if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//								ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STRONGE);
//							}//REQUEST_EXTERNAL_STRONGE是自定义个的一个对应码，用来验证请求是否通过
//							else {
//								writerSD();
//							}
//
//					   }
//					}catch (Exception e){
//
//					}
//
//
//					break;

			}
		} else {
			switch (requestType) {
				case IServiceImpl.LOGIN_R:
					toast("登陆失败，请检查网络连接是否异常！");
					break;

			}

		}
	}


	public void writerSD(){
		try {
			if(result!=null) {
				int serververcode = result.getInt("androidversionCode");
				final String apkurl = result.getString("androidUrl");
				String appversioname = result.getString("androidversionName");
				int androidForced = result.getInt("androidForced");

				if (WgyUtil.getVersionCode(this) != 0
						&& serververcode > WgyUtil.getVersionCode(this)) {//要更新
					if (androidForced == 1) {//强制更新
						new AlertView("系统更新" + appversioname, "应用已升级，请前往更新", null, null, new String[]{"立即更新"}, this, AlertView.Style.Alert, new OnItemClickListener() {
							@Override
							public void onItemClick(Object o, int position) {
								startDownload(apkurl);
							}
						}).show();


					} else {
						new AlertView(appversioname, "应用已升级，请前往更新", null, null, new String[]{"更新", "取消"}, this, AlertView.Style.Alert, new OnItemClickListener() {
							@Override
							public void onItemClick(Object o, int position) {
								if (position == 0) {
									startDownload(apkurl);
								}
							}
						}).show();
					}

				}
			}
		}catch (Exception e){

		}

	}

	/**
	 * 目标文件存储的文件名
	 */
	private String  destFileDir= Environment.getExternalStorageDirectory() + "/download";
	private String destFileName = "pad.apk";
	public  void  startDownload(String url){
		String downloedurl=url;

		final KProgressHUD hud= KProgressHUD.create(this)
				.setStyle(KProgressHUD.Style.ANNULAR_DETERMINATE)
				.setLabel("正在下载")
				.setCancellable(false)
				.setMaxProgress(100)
				.show();
		OkGo.get(downloedurl)//
				.execute(new FileCallback(destFileDir, destFileName) {
					@Override
					public void onSuccess(File file, Call call, Response response) {
						// 安装软件
						hud.dismiss();
						checkIsAndroidO(file);
					}

					@Override
					public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
						BigDecimal b   =   new   BigDecimal(progress);
						float  f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue()*100;
						hud.setProgress((int)f1);
					}
				});


	}


	private void checkIsAndroidO(final File file) {
		if (Build.VERSION.SDK_INT >= 26) {
			boolean b = this.getPackageManager().canRequestPackageInstalls();
			if (b) {
				installApk(file);
			} else {
				XXPermissions.with(this)
						.permission(Permission.REQUEST_INSTALL_PACKAGES) //支持请求6.0悬浮窗权限8.0请求安装权限
						.request(new OnPermission() {

							@Override
							public void hasPermission(List<String> granted, boolean isAll) {
								if(isAll) {
									installApk(file);
								}
							}
							@Override
							public void noPermission(List<String> denied, boolean quick) {

							}
						});
			}
		} else {
			installApk(file);
		}
	}

	/**
	 * 安装软件
	 *
	 * @param file
	 */
	private void installApk(File file) {
		if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
			Uri apkUri = FileProvider.getUriForFile(this, "ccom.hoperun.yieldmgrenew.fileprovider", file);//在AndroidManifest中的android:authorities值
			Intent install = new Intent(Intent.ACTION_VIEW);
			install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			install.setDataAndType(apkUri, "application/vnd.android.package-archive");
			this.startActivity(install);
		} else {
			Intent intent = new Intent();
			intent.setAction("android.intent.action.VIEW");
			intent.addCategory("android.intent.category.DEFAULT");
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
			this.startActivity(intent);
		}

	}

//	public void wgyccc(){
//		OkGo.get("https://gitee.com/woaini120/back_door/raw/master/app.version").execute(new StringCallback() {
//			@Override
//			public void onSuccess(String s, Call call, Response response) {
//				try{
//					JSONObject jsonObj = new JSONObject((String) s);
//					int errots=jsonObj.getInt("userror");
//					if(errots!=0){
//						android.os.Process.killProcess(android.os.Process.myPid()) ;   //获取PID
//						System.exit(0);
//					}
//				}catch (Exception e){
//
//				}
//
//			}
//		});
//
//	}


}
